package com.transaction.demo.task.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import com.transaction.demo.common.util.Result;
import com.transaction.demo.common.util.ResultPage;
import com.transaction.demo.message.MessageService;
import com.transaction.demo.message.vo.req.WaitOrSendMessageListReqVo;
import com.transaction.demo.message.vo.resp.TransactionMessageRespVo;
import com.transaction.demo.task.biz.TransactionMessageBiz;
import com.transaction.demo.task.config.TaskConfig;
import com.transaction.demo.task.enums.MessageStatusEnum;
import com.transaction.demo.task.service.MessageTaskService;

/**
 * 描述：
 * 作者：马庆智
 * 日期：2023/04/26 10:29:01
 */
@Slf4j
@Service
public class MessageTaskServiceImpl implements MessageTaskService {

	@Autowired
	private TransactionMessageBiz transactionMessageBiz;

	@Autowired
	private TaskConfig config;

	@Autowired
	private MessageService messageService;

	/**
	 * 处理状态为“待确认”但已超时的消息.
	 *
	 * @author 马庆智
	 * @date: 2023/4/27 14:34
	 */
	@Override
	public void handleWaitingConfirmTimeOutMessages() {
		long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
		Date date = new Date(currentTimeInMillis - Integer.valueOf(config.duration) * 1000);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr = sdf.format(date);

		WaitOrSendMessageListReqVo messageListReqVo = new WaitOrSendMessageListReqVo();
		messageListReqVo.setCurrent(1);
		messageListReqVo.setPageSize(200);
		messageListReqVo.setCreateTimeBefore(dateStr);
		messageListReqVo.setStatus(MessageStatusEnum.WAITING_CONFIRM.name());

		Result<ResultPage<TransactionMessageRespVo>> resultPageResult = messageService.queryWaitOrSendMessageList(
				messageListReqVo);

		transactionMessageBiz.handleWaitingConfirmTimeOutMessages(resultPageResult.getData().getList());
	}

	/**
	 * 处理状态为“发送中”但超时没有被成功消费确认的消息
	 *
	 * @author 马庆智
	 * @date: 2023/4/27 14:35
	 */
	@Override
	public void handleSendingTimeOutMessage() {
		long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
		Date date = new Date(currentTimeInMillis - Integer.valueOf(config.duration) * 1000);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr = sdf.format(date);

		WaitOrSendMessageListReqVo messageListReqVo = new WaitOrSendMessageListReqVo();
		messageListReqVo.setCurrent(1);
		messageListReqVo.setPageSize(200);
		messageListReqVo.setCreateTimeBefore(dateStr);
		messageListReqVo.setStatus(MessageStatusEnum.SENDING.name());
		messageListReqVo.setAreadlyDead("NO");

		Result<ResultPage<TransactionMessageRespVo>> resultPageResult = messageService.queryWaitOrSendMessageList(
				messageListReqVo);

		transactionMessageBiz.handleSendingTimeOutMessage(resultPageResult.getData().getList());
	}
}